package com.mingqijia.gassafety.job.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.HistoryAlarm;
import com.mingqijia.gassafety.db.entity.Organization;
import com.mingqijia.gassafety.db.entity.vo.HangzhouHistoryAlarmVo;
import com.mingqijia.gassafety.db.entity.vo.HistoryAlarmVo;
import com.mingqijia.gassafety.db.entity.vo.LatestLogListVO;
import com.mingqijia.gassafety.db.mapper.AlertRecordSignMapper;
import com.mingqijia.gassafety.db.mapper.HistoryAlarmMapper;
import com.mingqijia.gassafety.db.mapper.OrganizationMapper;
import com.mingqijia.gassafety.job.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.job.request.ConsoleSkSupplierListRequest;
import com.mingqijia.gassafety.job.request.HzRecordLogRequest;
import com.mingqijia.gassafety.job.request.RecordLogRequest;
import com.mingqijia.gassafety.job.response.*;
import com.mingqijia.gassafety.job.service.CompanyService;
import com.mingqijia.gassafety.job.service.HistoryAlarmService;
import com.mingqijia.gassafety.job.service.OrganizationService;
import com.mingqijia.gassafety.job.service.UserPermissionService;
import com.mingqijia.gassafety.job.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.UserFuncCodePermissionDTO;
import com.mingqijia.gassafety.shared.enums.DealtType;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.HeaderUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageColumns;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.ORG_MAP_SUBSCODE;

/**
 * <p>
 * 报警器设备报警记录 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-08-08
 */
@Slf4j
@Service
public class HistoryAlarmServiceImpl extends ServiceImpl<HistoryAlarmMapper, HistoryAlarm> implements HistoryAlarmService {

    @Autowired
    ConfigureHolder holder;

    @Autowired
    HeaderUtil headerUtil;

    @Autowired
    OrganizationService organizationService;

    @Autowired
    CompanyService companyService;

    @Autowired
    UserPermissionService userPermissionService;

    @Autowired
    EquipmentCmpService equipmentCmpService;


    @Override
    public PageUtil<AlertLogResponse> getAlarmList(RecordLogRequest req) {
        List<AlertLogResponse> resultList = new ArrayList<>();
        //要最近的设备信息，从数据库里查询，
        LatestLogListVO vo = new LatestLogListVO();
        //1.查询条件封装
        BeanUtils.copyProperties(req, vo);

        //所属组织
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        if (!StringUtils.isEmpty(req.getSpId()) && !spId.equals(req.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(req.getSpId());
        }
        vo.setSpIds(spIds);
        Map<String, String> reasonMap = new HashMap<>();
        try {
            List<DictionaryItemRespDTO> alarmReasonDict = holder.getDictionaryByKeyNoCache(
                    Constants.ALARM_REASON, spId);
            reasonMap = alarmReasonDict.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getValue, DictionaryItemRespDTO::getName));
        } catch(Exception e) {
            log.info("getAlarmList-alarmReasonDict-error:{}", e.getMessage());
        }
        Map<String, String> alarmReasonMap = reasonMap;
        Page<HistoryAlarmVo> page = PageHelper.startPage(req.getPage(), req.getPageSize());
        List<HistoryAlarmVo> list = new ArrayList<>();
        //1.2页面模板
        if (req.getTemplateType() == null) {
            req.setTemplateType(headerUtil.getTemplateType());
        }

        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        vo.setFuncCodes(userFuncCodePermission.getFuncCodes());

        if(TemplateTypeEnum.TEMPLATE_TYPE_1.getCode() == req.getTemplateType()){
            list = baseMapper.getVccRecord(vo);
        }else if(TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == req.getTemplateType()) {
            list = baseMapper.getAsstRecord(vo);
        }
        //查询组织架构名称
        List<CompanyListResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap;
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyListResponse::getSpId, CompanyListResponse::getName));
        } else {
            companyNameMap = new HashMap<>();
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap;
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        } else {
            orgSubsCodeMap = new HashMap<>();
        }
        if (!CollectionUtils.isEmpty(list)) {
            //设备类型名称
            List<DictionaryItemRespDTO> equipmentTypeDictList = holder.getDictionaryByKeys(
                    EquipmentType.DICT_CODE, spIds);
            //行业类型名称
            List<DictionaryItemRespDTO> industryTypeDictList = holder.getIndustryTypeZJ(spIds);
            //设备厂商名称
            ConsoleSkSupplierListResponse listResponse = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", listResponse);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (listResponse != null && listResponse.getCode() == 0 && listResponse.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(listResponse.getData())) {
                supplierListVos = listResponse.getData();
            }
            //运营商列表
            List<DictionaryItemRespDTO> operatorList = holder.getDictionaryByKey(Constants.OPERATOR_CODE);
            //组织名称列表
            List<OrganizationResponse> organizationList = organizationService.getList(ApplicationUtils.getWorkingSpId());

            List<AlarmSupplierListVo> finalSupplierListVos = supplierListVos;
            resultList = list.stream().map(historyAlarmVo -> {
                AlertLogResponse response = new AlertLogResponse();
                BeanUtils.copyProperties(historyAlarmVo, response);
                response.setXlel(historyAlarmVo.getConcentration() + " %LEL");
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyAlarmVo.getOrgCode()) && orgSubsCodeMap.containsKey(historyAlarmVo.getOrgCode())) {
                    response.setCompanyName(orgSubsCodeMap.get(historyAlarmVo.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(historyAlarmVo.getSpId())) {
                        response.setCompanyName(companyNameMap.get(historyAlarmVo.getSpId()));
                    }
                }
                // 报警原因
                response.setValveBrokenInfo(alarmReasonMap.get(historyAlarmVo.getBrokenInfo()) == null ? Constants.BLANK : alarmReasonMap.get(historyAlarmVo.getBrokenInfo()));
                //处理人信息
                if (!StringUtils.isEmpty(historyAlarmVo.getUserName()) && !StringUtils.isEmpty(historyAlarmVo.getUserAccount())){
                    response.setUserInfo(historyAlarmVo.getUserName() + "(" + historyAlarmVo.getUserAccount()+ ")");
                }else if (StringUtils.isEmpty(historyAlarmVo.getUserName()) && !StringUtils.isEmpty(historyAlarmVo.getUserAccount())){
                    response.setUserInfo( historyAlarmVo.getUserAccount());
                }else if (!StringUtils.isEmpty(historyAlarmVo.getUserName()) && StringUtils.isEmpty(historyAlarmVo.getUserAccount())){
                    response.setUserInfo(historyAlarmVo.getUserName());
                }
                //处理状态
                response.setAppealStatusMsg(AppealStateEnum.matcher(historyAlarmVo.getAppealStatus()).getMsg());
                //设置设备类型名称
                response.setEquipmentTypeName(getName(equipmentTypeDictList, historyAlarmVo.getEquipmentType()));
                //设置行业类型名称
                response.setIndustryTypeName(getName(industryTypeDictList, historyAlarmVo.getIndustryType()));
                //运营商
                response.setOperators(getName(operatorList, historyAlarmVo.getOperators()));
                //设置设备厂商
                response.setEquipmentManufacturer(finalSupplierListVos.stream().filter(a->a.getAlarmSystemCode().equals(
                        historyAlarmVo.getEquipmentManufacturer())).collect(Collectors.toList()).get(0).getMsName());
                //紫荆设备 联系人手机号
                if (historyAlarmVo.getEquipmentFrom() == Constants.ZJ_EQUIPMENT_FROM){
                    response.setContactPhone(historyAlarmVo.getPhone());
                }
                //所属组织
                if(!CollectionUtils.isEmpty(organizationList)){
                    List<OrganizationResponse> collect = organizationList.stream()
                            .filter(a -> a.getSpId().equals(historyAlarmVo.getSpId())).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(collect)){
                        response.setSpName(collect.get(0).getSpName());
                    }
                }
                //电磁阀信息
                response.setHasValve(historyAlarmVo.getValveInfoId() == 0 ? "-":"有");
                return response;
            }).collect(Collectors.toList());
        }

        PageUtil pageInfo = new PageUtil<>(req.getPage(), req.getPageSize(), page.getTotal(), resultList);

        return pageInfo;
    }

    private String getName(List<DictionaryItemRespDTO> list, String  value) {
        if( !CollectionUtils.isEmpty(list)){
            List<DictionaryItemRespDTO> respDTOS = list.stream()
                    .filter(dict -> dict.getValue().equals(value)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(respDTOS)){
                return respDTOS.get(0).getName();
            }
        }
        return null;
    }

    @Override
    public PageUtil<HangzhouAlertLogResponse> getHangZhouAlarmList(RecordLogRequest req) {
        List<AlertLogResponse> resultList = new ArrayList<>();
        //要最近的设备信息，从数据库里查询，
        LatestLogListVO vo = new LatestLogListVO();
        //1.查询条件封装
        BeanUtils.copyProperties(req, vo);

        //1.1所属组织
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        if (!StringUtils.isEmpty(req.getSpId()) && !spId.equals(req.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(req.getSpId());
        }
        vo.setSpIds(spIds);
        if (req.getTemplateType() == null) {
            req.setTemplateType(headerUtil.getTemplateType());
        }
        Page<HistoryAlarmVo> page = PageHelper.startPage(req.getPage(), req.getPageSize());
        List<HangzhouHistoryAlarmVo> list = new ArrayList<>();

        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        vo.setFuncCodes(userFuncCodePermission.getFuncCodes());
        //页面不完全返回结果封装
        if(TemplateTypeEnum.TEMPLATE_TYPE_1.getCode() == req.getTemplateType()){
            list = baseMapper.hzGetRecordWithType1(vo);
        }else if(TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == req.getTemplateType()) {
            list = baseMapper.hzGetRecordWithType2(vo);
        }
        log.info("getHangZhouAlarmList-list:{}", JSONObject.toJSONString(list));
        if (!CollectionUtils.isEmpty(list)) {
            //设备类型名称
            List<DictionaryItemRespDTO> equipmentTypeDictList = holder.getDictionaryByKey(
                    EquipmentType.DICT_CODE);
            //行业类型名称
            List<DictionaryItemRespDTO> industryTypeDictList = holder.getIndustryTypeZJ(spIds);
            //设备厂商名称
            ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", response);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
                supplierListVos = response.getData();
            }
            //组织名称列表
            List<OrganizationResponse> organizationList = organizationService.getList(ApplicationUtils.getWorkingSpId());

            //查询组织架构名称
            List<CompanyListResponse> companyNameList = companyService.queryCompanyNameList(spIds);
            Map<String, String> companyNameMap;
            if (!CollectionUtils.isEmpty(companyNameList)) {
                companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyListResponse::getSpId, CompanyListResponse::getName));
            } else {
                companyNameMap = new HashMap<>();
            }
            //批量查询字典
            List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
            Map<String, String> orgSubsCodeMap;
            if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
                orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
            } else {
                orgSubsCodeMap = new HashMap<>();
            }

            List<AlarmSupplierListVo> finalSupplierListVos = supplierListVos;
            resultList = list.stream().map(historyAlarmVo -> {
                HangzhouAlertLogResponse alertLogResponse = new HangzhouAlertLogResponse();
                BeanUtils.copyProperties(historyAlarmVo, alertLogResponse);
                alertLogResponse.setXlel(historyAlarmVo.getConcentration() + " %LEL");
                alertLogResponse.setConsumerId(historyAlarmVo.getConsumerId());
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyAlarmVo.getOrgCode()) && orgSubsCodeMap.containsKey(historyAlarmVo.getOrgCode())) {
                    alertLogResponse.setCompanyName(orgSubsCodeMap.get(historyAlarmVo.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(historyAlarmVo.getSpId())) {
                        alertLogResponse.setCompanyName(companyNameMap.get(historyAlarmVo.getSpId()));
                    }
                }
                //设置设备类型名称
                if( !CollectionUtils.isEmpty(equipmentTypeDictList)){
                    List<DictionaryItemRespDTO> collect = equipmentTypeDictList.stream()
                            .filter(dict -> dict.getValue().equals(historyAlarmVo.getEquipmentType()))
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)){
                        alertLogResponse.setEquipmentTypeName(collect.get(0).getName());
                    }
                }

                //设置行业类型名称
                if (!CollectionUtils.isEmpty(industryTypeDictList)){
                    List<DictionaryItemRespDTO> dto = industryTypeDictList.stream()
                            .filter(dict -> dict.getValue().equals(historyAlarmVo.getIndustryType()))
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(dto)){
                        alertLogResponse.setIndustryTypeName(dto.get(0).getName());
                    }
                }
                //设备厂商
                if (!StringUtils.isEmpty(historyAlarmVo.getEquipmentManufacturer())) {
                    alertLogResponse.setEquipmentManufacturer(finalSupplierListVos.stream().filter(a->a.getAlarmSystemCode().equals(
                            alertLogResponse.getEquipmentManufacturer())).collect(Collectors.toList()).get(0).getMsName());
                }
                //处理类型
                if (!StringUtils.isEmpty(historyAlarmVo.getDealtType())) {
                    alertLogResponse.setDealtType(DealtType.parse(historyAlarmVo.getDealtType()).getName());
                }
                //处理结果
                if(historyAlarmVo.getDealtResult() != null){
                    alertLogResponse.setDealtResult( historyAlarmVo.getDealtResult() == 0 ? "未办结 " : "已办结");
                }
                //所属组织
                if(!CollectionUtils.isEmpty(organizationList)){
                    List<OrganizationResponse> collect = organizationList.stream()
                            .filter(a -> a.getSpId().equals(historyAlarmVo.getSpId())).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(collect)){
                        alertLogResponse.setSpName(collect.get(0).getSpName());
                    }
                }
                return alertLogResponse;
            }).collect(Collectors.toList());
        }

        PageUtil pageInfo = new PageUtil<>(req.getPage(), req.getPageSize(), page.getTotal(), resultList);
        return pageInfo;
    }


}
